package com.mk.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Date;

public class UploadToken {
    private static final String access_key = "VcU4tLd0Y2pk_h_2RjE5YvnKgem29QAJyeBqEFyq";
    private static final String secret_key = "enBmm7jgVVz7VmHG_Jyt-1Q3yjGs7tIlyK-4Pl7u";

    public static String token(String bucket_name){
        String key1 = AESEncrypt(bucket_name, access_key);
        return AESEncrypt(key1, secret_key) + ":" + AESEncrypt(Long.toString(new Date().getTime()), secret_key);
    }

    private static final String DEFAULT_CODING = "utf-8";

    /**
     * 加密
     *
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    private static String AESEncrypt(String content, String key) {
        try {
            byte[] input = content.getBytes(DEFAULT_CODING);

            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));
            SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skc);

            byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
            int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
            cipher.doFinal(cipherText, ctLength);
            return parseByte2HexStr(cipherText);
        } catch (Exception ignored) {

        }
        return null;
    }

    /**
     * 字节转16进制数组
     *
     * @param buf
     * @return
     * @author lmiky
     * @date 2014-2-25
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (byte aBuf : buf) {
            String hex = Integer.toHexString(aBuf & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(token("demo-test"));
    }
}
